package com.example.wechat;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;

public class WebSocketService extends Service {
    private static final String TAG = "WebSocketService";
    private static final String WS_URL = "ws://your-websocket-server-url/ws";
    private final IBinder binder = new WebSocketBinder();
    private WebSocket webSocket;
    private OkHttpClient client;
    private WebSocketCallback callback;

    public class WebSocketBinder extends Binder {
        public WebSocketService getService() {
            return WebSocketService.this;
        }
    }

    public interface WebSocketCallback {
        void onMessageReceived(String message);
        void onConnectionStatusChanged(boolean isConnected);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        client = new OkHttpClient.Builder()
                .readTimeout(0, TimeUnit.MILLISECONDS)
                .build();
        connectWebSocket();
    }

    private void connectWebSocket() {
        Request request = new Request.Builder()
                .url(WS_URL)
                .build();

        webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                Log.d(TAG, "WebSocket连接已打开");
                if (callback != null) {
                    callback.onConnectionStatusChanged(true);
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                Log.d(TAG, "收到消息: " + text);
                if (callback != null) {
                    callback.onMessageReceived(text);
                }
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                Log.d(TAG, "收到二进制消息");
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                Log.d(TAG, "WebSocket正在关闭");
                webSocket.close(1000, null);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                Log.e(TAG, "WebSocket连接失败", t);
                if (callback != null) {
                    callback.onConnectionStatusChanged(false);
                }
                // 尝试重新连接
                reconnect();
            }
        });
    }

    private void reconnect() {
        try {
            Thread.sleep(5000); // 等待5秒后重连
            connectWebSocket();
        } catch (InterruptedException e) {
            Log.e(TAG, "重连等待被中断", e);
        }
    }

    public void sendMessage(String message) {
        if (webSocket != null) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "text");
                jsonObject.put("content", message);
                webSocket.send(jsonObject.toString());
            } catch (Exception e) {
                Log.e(TAG, "发送文本消息失败", e);
            }
        }
    }

    public void sendImage(String imageUrl) {
        if (webSocket != null) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "image");
                jsonObject.put("url", imageUrl);
                webSocket.send(jsonObject.toString());
            } catch (Exception e) {
                Log.e(TAG, "发送图片消息失败", e);
            }
        }
    }

    public void sendVoice(String voiceUrl, int duration) {
        if (webSocket != null) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("type", "voice");
                jsonObject.put("url", voiceUrl);
                jsonObject.put("duration", duration);
                webSocket.send(jsonObject.toString());
            } catch (Exception e) {
                Log.e(TAG, "发送语音消息失败", e);
            }
        }
    }

    public void setCallback(WebSocketCallback callback) {
        this.callback = callback;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webSocket != null) {
            webSocket.close(1000, "Service destroyed");
        }
    }
}